#include <atspi/atspi.h>
#include <stdio.h>
#include <unistd.h>

// 查找特定名称的应用程序
AtspiAccessible *find_application(const char *app_name)
{
    AtspiAccessible *desktop = atspi_get_desktop(0);
    gint child_count = atspi_accessible_get_child_count(desktop, NULL);

    for (gint i = 0; i < child_count; i++)
    {
        AtspiAccessible *child = atspi_accessible_get_child_at_index(desktop, i, NULL);
        const gchar *name = atspi_accessible_get_name(child, NULL);

        if (name && g_strcmp0(name, app_name) == 0)
        {
            g_object_unref(desktop);
            return child;
        }
        g_object_unref(child);
    }

    g_object_unref(desktop);
    return NULL;
}

// 递归打印无障碍对象树
void print_accessible_tree(AtspiAccessible *obj, int level)
{
    if (!obj)
        return;

    // 打印缩进
    for (int i = 0; i < level; i++)
    {
        if (i == level - 1)
        {
            printf("|——");
        }
        else
            printf("   ");
    }

    // 打印对象信息
    const gchar *name = atspi_accessible_get_name(obj, NULL);
    const gchar *role_name = atspi_accessible_get_role_name(obj, NULL);
    printf("%s (角色: %s)\n", (g_strcmp0(name, "") != 0 && name) ? name : "无名称", role_name ? role_name : "未知");

    // 如果是文本对象，打印文本内容
    AtspiText *text = atspi_accessible_get_text(obj);
    if (text)
    {
        gchar *content = atspi_text_get_text(text, 0, -1, NULL);
        for (int i = 0; i < level; i++)
        {
            printf("   ");
        }
        printf("文本内容: %s\n", content);
        g_free(content);
        g_object_unref(text);
    }

    // 递归处理子对象
    gint child_count = atspi_accessible_get_child_count(obj, NULL);
    for (gint i = 0; i < child_count; i++)
    {
        AtspiAccessible *child = atspi_accessible_get_child_at_index(obj, i, NULL);
        print_accessible_tree(child, level + 1);
        g_object_unref(child);
    }
}

int main()
{
    // 初始化ATSPI
    atspi_init();

    // 等待GTK应用程序启动
    printf("等待无障碍示例程序启动...\n");
    sleep(2);

    // 查找我们的GTK应用程序
    AtspiAccessible *app = find_application("simple_gtk_app");
    if (!app)
    {
        printf("未找到无障碍示例程序，请确保它正在运行\n");
        atspi_exit();
        return 1;
    }

    printf("找到应用程序: %s\n", atspi_accessible_get_name(app, NULL));
    printf("无障碍对象树:\n");
    print_accessible_tree(app, 0);

    // 释放资源
    g_object_unref(app);
    atspi_exit();
    return 0;
}